package com.googlecode.bpmcenter.util;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

public class ImageUtil {

	public static String getFormat(InputStream stream) throws IOException {
		ImageInputStream iis = ImageIO.createImageInputStream(stream);
		Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
		if (!iter.hasNext()) {
			throw new IOException("Unsupported image format!");
		}
		ImageReader reader = (ImageReader) iter.next();
		iis.close();
		return reader.getFormatName();
	}

	public static BufferedImage loadImage(InputStream stream) throws IOException {
		return ImageIO.read(stream);
	}

	public static void saveImageAsJPEG(BufferedImage image, OutputStream stream) throws IOException {
		ImageIO.write(image, "jpg", stream);
	}

	public static void saveImageAsJPEG(BufferedImage image, OutputStream stream, int qualityPercent) throws IOException {
		if ((qualityPercent < 0) || (qualityPercent > 100)) {
			throw new IllegalArgumentException("Quality out of bounds!");
		}
		float quality = qualityPercent / 100f;
		ImageWriter writer = null;
		Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
		if (iter.hasNext()) {
			writer = (ImageWriter) iter.next();
		}
		ImageOutputStream ios = ImageIO.createImageOutputStream(stream);
		writer.setOutput(ios);
		ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
		iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		iwparam.setCompressionQuality(quality);
		writer.write(null, new IIOImage(image, null, null), iwparam);
		ios.flush();
		writer.dispose();
		ios.close();
	}

	public static void saveImageAsPNG(BufferedImage image, OutputStream stream) throws IOException {
		ImageIO.write(image, "png", stream);
	}

}
